import Taro, { useState, useEffect, useCallback } from '@tarojs/taro';
import { View, Text, ScrollView } from '@tarojs/components';
import Utils from '../../../utils/index';
import { AtTabs, AtTabsPane, AtCard, AtActivityIndicator, AtDivider } from 'taro-ui';
import './index.less';
import http from '../../../utils/request';
import { Result } from '../../../model/index';
import NavBar from '../../../components/navBar';

const ToDaysLine = () => {
  const [todayList, setTodayList] = useState<any[]>([]);
  const [current, setCurrent] = useState<number>(0);
  const [tabList, setTabList] = useState<Array<{ title: string }>>([
    {
      title: '头条',
    },
    {
      title: '新闻',
    },
  ]);
  const [loading, setLoading] = useState(true);
  const [paging, setPaging] = useState({
    page: 1,
    status: false,
  });
  // 初始化
  useEffect(() => {
    // getNewTabs();
    getNewRecom();
  }, [getNewRecom]);
  // 获取新闻频道
  const getNewTabs = () => {
    const url = `new/types`;
    http.get(url).then((res: Result) => {
      if (res && res.data.status === 1) {
        const data = res.data.data;
      }
    });
  };
  // 获取推荐列表
  // @ts-ignore
  const getNewRecom = useCallback((channel = '头条', page?: number) => {
    const url = `new/recom`;
    setLoading(true);
    http.get(url, { channel, start: page ? page : paging.page }).then((res: Result) => {
      if (res && res.data.data.code === '10000') {
        const data = res.data.data.result.result.list;
        if (data.length < 10) {
          setPaging({
            page: 1,
            status: true,
          });
        }
        if (page === 1) {
          setTodayList(data);
        } else {
          setTodayList(todayList.concat(data));
        }
        setLoading(false);
      }
    });
  });
  // 格式化数据
  const formatContent = (res: string) => {
    const result = JSON.parse(res);
    return result;
  };
  // 滚动到顶部
  const onScrollToUpper = () => {
    console.log('滚动到顶部了');
  };
  // 滚动到底部
  const onscrollToLower = () => {
    console.log('滚动到底部了');
    if (!paging.status) {
      setPaging({
        page: paging.page + 1,
        status: false,
      });
      tabListContent(current, paging.page + 1);
    }
  };
  // 跳转详情页面
  const GoToDetail = val => {
    const data = JSON.stringify(val);
    Taro.setStorage({ key: 'todays', data: data });
    Taro.navigateTo({
      url: '/pages/home/todays-line/detail/index',
    });
  };
  // 点击tabs
  const handleClick = (val: number) => {
    setTodayList([]);
    setPaging({
      status: false,
      page: 1,
    });
    setCurrent(val);
    tabListContent(val, 1);
  };
  const onScroll = val => {
    // console.log(val);
  };
  // tabs列表展示
  const tabListContent = (val?: number, page?: number) => {
    switch (val ? val : current) {
      case 0:
        getNewRecom('头条', page);
        break;
      case 1:
        getNewRecom('新闻', page);
    }
  };
  const scrollTop = 0;
  const Threshold = 100;
  return (
    <View>
      {process.env.TARO_ENV === 'h5' ? <NavBar title="新闻" /> : null}
      <AtTabs className="tabs" current={current} tabList={tabList} onClick={handleClick}>
        {tabList.map((item, index) => {
          return (
            <AtTabsPane key={item.title} current={current} index={index}>
              <ScrollView
                style={Utils.scrollTopHeight}
                scrollY
                scrollWithAnimation
                scrollTop={scrollTop}
                lowerThreshold={Threshold}
                upperThreshold={Threshold}
                onScrollToLower={onscrollToLower}
                onScrollToUpper={onScrollToUpper} // 使用箭头函数的时候 可以这样写 `onScrollToUpper={this.onScrollToUpper}`
                onScroll={onScroll}
              >
                <View className="container">
                  {todayList.map((res: any) => {
                    return (
                      <AtCard
                        className="card"
                        key={res.title}
                        note={res.time}
                        extra={res.category}
                        title={res.src}
                        thumb={res.pic}
                        onClick={() => {
                          GoToDetail(res);
                        }}
                      >
                        {res.title}
                      </AtCard>
                    );
                  })}
                  {/* 暂无更多数据 */}
                  {paging.status ? <AtDivider content="没有更多了" fontColor="#2d8cf0" lineColor="#2d8cf0" /> : null}
                  {/* 加载中... */}
                  {loading ? <AtActivityIndicator mode="center"></AtActivityIndicator> : null}
                </View>
              </ScrollView>
            </AtTabsPane>
          );
        })}
      </AtTabs>
    </View>
  );
};

ToDaysLine.config = {
  navigationBarTitleText: '新闻',
};
export default ToDaysLine;
